/**
 * 
 */
package com.fox.webapp.schedule;

import java.io.IOException;
import java.util.List;

import javax.mail.MessagingException;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.fox.webapp.domain.Account;
import com.fox.webapp.domain.AccountVerifySetting;
import com.fox.webapp.domain.Broker;
import com.fox.webapp.persistent.AccountRepository;
import com.fox.webapp.persistent.AccountVerifySettingRepository;
import com.fox.webapp.persistent.BrokerRepository;
import com.fox.webapp.service.IAsyncActionService;
import com.fox.webapp.service.IEmailService;

/**
 * 账户验证任务调度<br>
 * 每个broker都需要进行配置后才能认证<br>
 * 配置信息: <br>
 * <table>
 *   <thead>
 *     <tr>
 *       <td>Broker</td>
 *       <td>loginUrl</td>
 *       <td>loginData</td>
 *       <td>sessionIdKey</td>
 *       <td>accountsUrl</td>
 *       <td>accountsElementsSelector</td>
 *     </tr>
 *   </thead>
 *   <tbody>
 *   	<tr>
 *   		<td>Exness</td>
 *   		<td>https://www.exness.com/intl/zh/member</td>
 *   		<td>Platform,mt4,Login,5180,Password,xuyuqi1986</td>
 *   		<td>ss</td>
 *   		<td>https://www.exness.com/intl/zh/member/partnership</td>
 *   		<td>.accountHistory table tr td:eq(0)</td>
 *   	</tr>
 *   	<tr>
 *   		<td>Nordfx</td>
 *   		<td>https://account.nordfx.com/account/</td>
 *   		<td>login,300340,password,4eW29eK0C6</td>
 *   		<td>NFX_SESSION5</td>
 *   		<td></td>
 *   		<td></td>
 *   	</tr>
 *   </tbody>
 *  </table>
 * @author yockii
 *
 */
@Component
public class AccountVerifySchedule {

	private final static Logger logger = LoggerFactory.getLogger(AccountVerifySchedule.class);
	
	@Autowired
	private AccountRepository accountRepository;
	@Autowired
	private BrokerRepository brokerRepository;
	@Autowired
	private AccountVerifySettingRepository accountVerifySettingRepository;
	@Autowired
	private IAsyncActionService emailService;
	
	@Scheduled(fixedDelay = 15 * 60 * 1000)
	public void verifyNotActivedAccount() {
		List<AccountVerifySetting> settings = (List<AccountVerifySetting>) accountVerifySettingRepository.findAll();
		for (AccountVerifySetting setting : settings) {
			try {
				verifyOneBroker(setting);
			} catch (Exception e) {
				e.printStackTrace();
				emailService.sendErrorMessageAsync(e.getMessage());
			}
		}
	}
	
	private void verifyOneBroker(AccountVerifySetting setting) throws IOException {
		Broker broker = brokerRepository.findByNameIgnoreCase(setting.getBrokerName());
		List<Account> as = accountRepository.findByBrokerAndActiveIsNull(broker);
		if(as.size() == 0){
			return;
		}
		
		Connection.Response res = Jsoup.connect(setting.getLoginUrl()).data(setting.getLoginData().split(",")).method(Method.POST).execute();
		String sessionId = res.cookie(setting.getSessionIdKey());
		if(StringUtils.hasText(sessionId)){
			Document doc = Jsoup.connect(setting.getAccountsUrl()).cookie(setting.getSessionIdKey(), sessionId).get();
			Elements accountElements = doc.select(setting.getAccountsElementsSelector());
			for (Element element : accountElements) {
				String accountNo = element.html();
				for (int i = as.size() - 1; i >= 0; i--) {
					Account account = as.get(i);
					if(accountNo.equals(account.getAccountNo().toString())){
						account.setActive(true);
						accountRepository.activeAccount(account);
						as.remove(i);
					}
				}
			}
			for (Account account : as) {
				account.setActive(false);
				accountRepository.activeAccount(account);
			}
		}
	}

	/*
	public void lookingForExness() throws IOException {
		Connection.Response res = Jsoup.connect("https://www.exness.com/intl/zh/member")
				.data("Platform", "mt4", "Login", "5180", "Password", "xuyuqi1986")
				.method(Method.POST)
				.execute();
//		Document doc = res.parse();
//		for (String cookie : res.cookies().keySet()) {
//			logger.debug(cookie + ": " + res.cookie(cookie));
//		}
		
		String sessionId = res.cookie("ss");
		
		if(StringUtils.hasText(sessionId)){
			// get broker
			Broker exness = brokerRepository.findByNameIgnoreCase("Exness");
			// get accountType
			List<AccountType> atList = accountTypeRepository.findByBroker(exness);
			
			List<Account> accountList = new ArrayList<Account>();
			// Get All Not Actived Account Which Is Exness
			for (AccountType at : atList) {
				List<Account> noActivedExnessAccountList = accountRepository.findByAccountTypeAndActiveIsNull(at);
				accountList.addAll(noActivedExnessAccountList);
			}
			
			if(accountList.size() == 0){
				return;
			}
			Document doc = Jsoup.connect("https://www.exness.com/intl/zh/member/partnership").cookie("ss", sessionId).get();
			
			
			Elements accountNoEles = doc.select(".accountHistory table tr td:eq(0)");
			for(Element ele : accountNoEles){
				String accountNo = ele.html();
//				logger.debug(accountNo);
				
				for (int i = accountList.size() - 1; i >= 0; i--) {
					Account account = accountList.get(i);
					if(accountNo.equals(account.getAccountNo().toString())){
						account.setActive(true);
						accountRepository.activeAccount(account);
						accountList.remove(i);
					}
				}
			}
			for (Account account : accountList) {
				account.setActive(false);
				accountRepository.activeAccount(account);
			}
		}
	}
	
	public void lookingForNordFx() throws IOException{
		Connection.Response res = Jsoup.connect("https://account.nordfx.com/account/")
				.data("login", "300340", "password", "4eW29eK0C6")
				.method(Method.POST)
				.execute();
		
		String sessionId = res.cookie("NFX_SESSION5");
		
		if(StringUtils.hasText(sessionId)){
			// get broker
			Broker nordfx = brokerRepository.findByNameIgnoreCase("nordfx");
			// get accountType
			List<AccountType> atList = accountTypeRepository.findByBroker(nordfx);
			
			List<Account> accountList = new ArrayList<Account>();
			// Get All Not Actived Account Which Is Exness
			for (AccountType at : atList) {
				List<Account> al = accountRepository.findByAccountTypeAndActiveIsNull(at);
				accountList.addAll(al);
			}
			
			if(accountList.size() == 0){
				return;
			}
			
			////////////////////////////////////////////////////////////////////////
			Document doc = Jsoup.connect("https://www.exness.com/intl/zh/member/partnership").cookie("NFX_SESSION5", sessionId).get();
			Element tableDiv = doc.getElementsByClass("accountHistory").first();
			
			Element table = tableDiv.getElementsByTag("table").first();
			Elements rows = table.getElementsByTag("tr");
			
			for (Element row : rows) {
				String accountNo = row.getElementsByTag("td").first().html();
				for (int i = accountList.size() - 1; i >= 0; i--) {
					Account account = accountList.get(i);
					if(accountNo.equals(account.getAccountNo().toString())){
						account.setActive(true);
						accountRepository.activeAccount(account);
						accountList.remove(i);
					}
				}
			}
			
			for (Account account : accountList) {
				account.setActive(false);
				accountRepository.activeAccount(account);
			}
		}
	}
	*/
	public static void main(String[] args) throws IOException {
		Connection.Response res = Jsoup.connect("https://account.nordfx.com/account/")
				.data("login", "300340", "password", "4eW29eK0C6")
				.method(Method.POST)
				.execute();
//		Document doc = res.parse();
		for (String cookie : res.cookies().keySet()) {
			logger.debug(cookie + ": " + res.cookie(cookie));
		}
	}
}
